<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:csharp="http://csharp.org" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">

  <msxsl:script language="CSharp" implements-prefix="csharp">
    <![CDATA[
      public string GetAddressFromLatLon(string lat, string lon)
      {
        // if either is null, then assume we have nothing
        if(lat == null || lon == null)
        {
          lat = "0.0";
          lon = "0.0";
        }
        
        // this is the default string to send if we don't find a legit address
        // string address = string.Format("Lat, Lon: {0}, {1}", lat, lon);
		string address = "";
        try
        {
          // build the url to get the address from Google Geocoder
          string url = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", lat, lon);
          
          // parse the XML
          XmlDocument doc = new XmlDocument();
          doc.Load(url);

          // Make sure the status of the response is "OK"
          XmlNode statusNode = doc.SelectSingleNode("//GeocodeResponse/status");
          if (statusNode != null)
          {
            string status = statusNode.InnerText;
            if (string.Compare(status, "ok", true) == 0)
            {
              // Loop through the results
              XmlNodeList resultNodes = doc.SelectNodes("//GeocodeResponse/result");
              foreach (XmlNode resultNode in resultNodes)
              {
                XmlNode typeNode = resultNode.SelectSingleNode("type");
                if (typeNode != null)
                {
                  // If the result type is a street address
                  string type = typeNode.InnerText;
                  if (string.Compare(type, "street_address", true) == 0 || string.Compare(type, "route", true) == 0)
                  {
                    XmlNode addrNode = resultNode.SelectSingleNode("formatted_address");
                    if (addrNode != null)
                    {
                      // use the address given
                      address = addrNode.InnerText;
                      break;
                    }
                  }
                }
              }
            }
          }
        }
        catch (Exception e) 
        { 
          // do nothing 
        }
        return address;
      }
    ]]>
  </msxsl:script>
</xsl:stylesheet>
